package com.lesama.correspondence;

/*
notify() 随机唤醒一个线程
notifyAll() 唤醒所有线程
sleep 与wait方法的区别
sleep: 方法为线程休眠， 时间到了自动醒来，sleep方法在休眠时间内不会释放锁
wait: 方法为线程等待，需要由其他线程notify唤醒，wait方法等待期间会释放锁
 */

public class CorrespondenceDemo2 {
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        synchronized (Printer2.class) {
                            new Printer2().print1();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        synchronized (Printer2.class) {
                            new Printer2().print2();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        synchronized (Printer2.class) {
                            new Printer2().print3();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }
}

class Printer2 {
    private static int flag = 1;
    public void print1() throws InterruptedException {
        while(flag != 1) {
            Printer2.class.wait(); // flag不为1，让线程等待
        }
        System.out.print("鸣");
        System.out.print("濑");
        System.out.print("白");
        System.out.println("羽");

        flag = 2; // 线程处理完，通知其他线程
        Printer2.class.notifyAll();
    }

    public void print2() throws InterruptedException {
        while(flag != 2) {
            Printer2.class.wait();
        }
        System.out.print("空");
        System.out.print("门");
        System.out.println("苍");

        flag = 3;
        Printer2.class.notifyAll();
    }

    public void print3() throws InterruptedException {
        while(flag != 3) {
            Printer2.class.wait();
        }
        System.out.print("久");
        System.out.print("岛");
        System.out.println("鸥");

        flag = 1;
        Printer2.class.notifyAll();
    }
}